package com.gs.netty.support.resolver;

import com.alibaba.fastjson2.JSON;


import com.gs.netty.core.SerializableEnum;
import com.gs.netty.core.annotation.CommandExceptionHandler;
import com.gs.netty.core.resolver.HandlerMethodReturnValueHandler;
import com.gs.netty.websocket.remoting.WebSocketInvocation;
import com.gs.netty.websocket.remoting.req.NativeWebSocketRequest;
import com.gs.netty.websocket.remoting.resp.AppResponse;
import org.springframework.core.MethodParameter;

/**
 * 异常结果处理器
 */

public class ExceptionHandlerMethodReturnValueHandler implements HandlerMethodReturnValueHandler<NativeWebSocketRequest> {


    public ExceptionHandlerMethodReturnValueHandler() {
    }

    @Override
    public boolean supportsReturnType(MethodParameter returnType) {

        CommandExceptionHandler exceptionHandler = returnType.getMethodAnnotation(CommandExceptionHandler.class);

        return null != exceptionHandler &&  SerializableEnum.JSON.equals(exceptionHandler.serializable());
    }
    @Override
    public void handleReturnValue(Object returnValue, MethodParameter returnType, NativeWebSocketRequest request) {
        String body;
        if (returnValue instanceof CharSequence) {
            body = returnValue.toString();
        }else {
            body =  JSON.toJSONString(returnValue);
        }
        CommandExceptionHandler exceptionHandler = returnType.getMethodAnnotation(CommandExceptionHandler.class);

        WebSocketInvocation response = request.createResponse();

        response.setStatus(exceptionHandler.statusCode());
//        response.setPayload(body);
        request.getNativeResponse().writeAndFlush(response);

    }
}
